//
//  SearchPriceDetail.m
//  HappyStore
//
//  Created by 李小辉 on 16/6/1.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "SearchPriceDetail.h"
#import "goveDetailVC.h"
#import "thirdPersonVC.h"
#import "PriceView.h"
#import "recommendViC.h"
#import "PinLunCell.h"
#import "PinLunVC.h"
#import "WriteComment.h"
@interface SearchPriceDetail ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (strong, nonatomic) UITableView *tableView;//评论tabelView
@property (assign,nonatomic) NSInteger numHeight;//记录点击（展开/收起）的次数
@property (strong, nonatomic) PriceView *priceViewFir; //上半view

@property (strong, nonatomic) recommendViC *recommendview;

@property (assign, nonatomic) NSInteger labelHeight;//记录描述的位置

@property (strong, nonatomic) NSString *isFocus;//判断收藏

@property (weak, nonatomic) IBOutlet UIButton *btnCollect;

@property (assign, nonatomic) NSInteger page;

@end

@implementation SearchPriceDetail



- (NSMutableArray *)commentsList{
    if (!_commentsList) {
        _commentsList = [NSMutableArray array];
    }
    return _commentsList;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
    }
    return _tableView;
}

-(recommendViC *)recommendview{
    if (!_recommendview) {
        _recommendview = [[recommendViC alloc] init];
    }
    return _recommendview;
}

-(NSDictionary *)dicData{
    if (!_dicData) {
        _dicData = [NSDictionary dictionary];
    }
    return _dicData;
}

-(PriceView *)priceViewFir{
    if (!_priceViewFir) {
        _priceViewFir = [[[NSBundle mainBundle] loadNibNamed:@"PriceView" owner:self options:nil] lastObject];
    }
    return _priceViewFir;
}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        //开始任务
        if (self.commentsList.count == 10) {
            self.scrollView.mj_footer.hidden = NO;
        }else{
            self.scrollView.mj_footer.hidden = YES;
        }
        self.isFocus = self.dicData[@"isfocus"];
        //NSLog(@"isFocus:%@",self.isFocus);
        
        if ([self.isFocus isEqualToString:@"是"]) {
            [self.btnCollect setImage:[UIImage imageNamed:@"评论点赞图标"] forState:UIControlStateNormal]; //[UIImage imageNamed:@"yishouchang_11"];
        }else{
            [self.btnCollect setImage:[UIImage imageNamed:@"资讯-点赞"] forState:UIControlStateNormal];
        //[UIImage imageNamed:@"shouchang_10"];
    }

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = NO;
    navBarHairlineImageView.alpha = 0.5f;
    
    [self setupPriceViewFir];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = YES;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"资金详情";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    self.fundsId= self.dicData[@"fundsId"];
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    if ([self.tig isEqualToString:@"price"]) {
        self.priceViewFir.jumpBtn.hidden = YES;
    }
    //点击头像跳转
    [self.priceViewFir.jumpBtn addTarget:self action:@selector(goGoveByNow) forControlEvents:UIControlEventTouchUpInside];
    //点击展开
    [self.priceViewFir.clickButton addTarget:self action:@selector(clickButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //监听点击
    [self.recommendview.recommendView.sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePinlun:) name:@"updatePinlun" object:nil];
    self.numHeight = 1;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    
    self.page = 1;
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}


- (void)updatePinlun: (NSNotification *)noti{
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:noti.userInfo];
    if ([dic[@"result"] integerValue] == 1) {
        self.page = 1;
        self.commentsList = nil;
        [self getMorePingLun];
    }
}

- (void)sureBtnClick{
    if (self.recommendview.recommendView.nameTextField.text.length < 1 || self.recommendview.recommendView.phoneTextField.text.length < 1) {

        [self showSingleIconBubble:@"请完善内容"];

    }else{
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        dic[@"resId"] = self.fundsId;
        dic[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
        dic[@"token"] = [USER_DEFAULTS objectForKey:@"token"];
        dic[@"type"] = @(2);
        dic[@"touchName"] = self.recommendview.recommendView.nameTextField.text;
        dic[@"touchWay"] = self.recommendview.recommendView.phoneTextField.text;
        
        [LSHttpTool sendHttpData:@"referralplatform_app_project.im.lensum" params:dic success:^(id responseObject) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"平台引荐成功！工作人员将在三日之内给您答复！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            
            
        } failure:^(NSError *error) {
            
            [self showSingleIconBubble:@"网络连接错误"];
            
        }];
        
    }
}


#pragma mark - 布局视图
//设置上半view
-(void)setupPriceViewFir{
    
    self.priceViewFir.titleLabel.text = self.dicData[@"title"];
    //---
//    self.priceViewFir.moneyLabel.text = [self comperNumber:self.dicData[@"investment"]];
    self.priceViewFir.moneyLabel.text = [UsedTool priceChange:self.dicData[@"investment"]];
    [self.priceViewFir.headImageView sd_setImageWithURL:self.dicData[@"headPhoto"] placeholderImage:[UIImage imageNamed:@"project_detail_heder_normal"]];
    self.priceViewFir.headImageView.layer.masksToBounds = YES;
    self.priceViewFir.headImageView.layer.cornerRadius = 25.0f;
    self.priceViewFir.qualityName.text = self.dicData[@"qualityName"];

    if (self.dicData[@"username"]==nil || [self.dicData[@"username"] isEqualToString:@""] ||[self.dicData[@"username"] isEqualToString:@"null"]) {
        self.priceViewFir.commentUserName.text = self.dicData[@"account"];
    }else{
        self.priceViewFir.commentUserName.text = self.dicData[@"username"];
    }
    self.priceViewFir.posiTion.text = self.dicData[@"posiTionName"];
    if (self.dicData[@"posiTionName"]==nil||[self.dicData[@"posiTionName"] isEqualToString:@"null"]) {
        self.priceViewFir.posiTion.text = @"";
    }
    //认证
    self.priceViewFir.isAuthState.hidden = [UsedTool authStateImageViewHidden:self.dicData[@"authState"]];
    //会员图标
    self.priceViewFir.authStateImageView.image = [UsedTool setVipimage:self.dicData[@"vipLevel"]];
    //判断上级
    self.priceViewFir.companyUserName.text = [UsedTool userType:self.dicData[@"userType"] companyName:self.dicData[@"companyName"] userAddress:self.dicData[@"userAddress"]];
    
    self.priceViewFir.descriptionLabel.text = self.dicData[@"description"];
    NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:self.priceViewFir.descriptionLabel.text];
    NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:8];
    [attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [self.priceViewFir.descriptionLabel.text length])];
    [self.priceViewFir.descriptionLabel setAttributedText:attributedString1];
    [self.priceViewFir.descriptionLabel sizeToFit];
    
    self.priceViewFir.descriptionLabel.textAlignment = NSTextAlignmentLeft;

    CGSize constraint = CGSizeMake(screenW-16, 2000.0f);
    CGSize size = [self.priceViewFir.descriptionLabel sizeThatFits:constraint];

    self.labelHeight = size.height;
    
    
    self.priceViewFir.frame = CGRectMake(0, 0, screenW, self.priceViewFir.descriptionLabel.y+size.height +100);
    
    [self.scrollView addSubview:self.priceViewFir];
    [self setupTableView];
    self.scrollView.contentSize = CGSizeMake(screenW, self.priceViewFir.height);
    
}


- (void)setupTableView{
    
    self.tableView.bounces = NO;
    self.tableView.frame = CGRectMake(0, self.priceViewFir.height +20, screenW, self.tableView.height);
    //self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, self.tableView.height, 0);

    [self.scrollView addSubview:self.tableView];
    //集成下拉加载更多评论
    [self setupDownRefresh];
    [self.tableView reloadData];
    
}
-(void)setupDownRefresh{
    
    self.scrollView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self getMorePingLun];
    }];
}

#pragma mark - 点击个人头像跳转
- (void)goGoveByNow{
    if ([self.dicData[@"userType"] integerValue] == 3) {
        goveDetailVC *goveVC = [[goveDetailVC alloc] init];
        goveVC.userId = self.dicData[@"userId"];
        goveVC.userType = self.dicData[@"userType"];
        [self.navigationController pushViewController:goveVC animated:YES];
        
    }else{
        thirdPersonVC *thirdVC = [[thirdPersonVC alloc] init];
        thirdVC.userId = self.dicData[@"userId"];
        thirdVC.userType = self.dicData[@"userType"];
        [self.navigationController pushViewController:thirdVC animated:YES];
        
    }
}

#pragma mark - tableView DataSource


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.commentsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *strCell = @"commentCell";
    UINib *nib = [UINib nibWithNibName:@"PinLunCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:strCell];
    PinLunCell *cell = [self.tableView dequeueReusableCellWithIdentifier:strCell];
    
    if (!cell) {
        cell = [[PinLunCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
    }
    NSDictionary *dic = self.commentsList[indexPath.row];
    
    cell.posiTion.text = dic[@"posiTion"];
    if (dic[@"posiTion"]==nil||[dic[@"posiTion"] isEqualToString:@"null"] ) {
        cell.posiTion.text = @"";
    }
    [cell.headPhotoImageView sd_setImageWithURL:dic[@"headPhoto"] placeholderImage:[UIImage imageNamed:@"20100403114758394_4147"]];
    cell.headPhotoImageView.layer.cornerRadius = 23.0f;
    cell.headPhotoImageView.layer.masksToBounds = YES;
    cell.userName.text = dic[@"commentUsername"];
    if (dic[@"commentUsername"]==nil||[dic[@"commentUsername"] isEqualToString:@""]||[dic[@"commentUsername"] isEqualToString:@"null"]) {
        cell.userName.text = dic[@"commentAccount"];
    }
    cell.timeLabel.text = [CustomExcetion prettyDateWithReference:[CustomExcetion dateFromString:dic[@"createTime"]]];
    //认证
    cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dic[@"authState"]];
    //会员图标
    cell.authStateImageView.image = [UsedTool setVipimage:dic[@"vipLevel"]];
    //判断上级
    cell.companyUserName.text = [UsedTool userType:dic[@"userType"] companyName:dic[@"companyName"] userAddress:dic[@"userAddress"]];
    cell.commentContent.text = dic[@"content"];
    CGSize sizeUserName = [cell.userName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    CGSize sizePosition = [cell.posiTion sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    //名字长度控制
    
    if (sizePosition.width == 0) {
        if (sizeUserName.width > 170.0f) {
            cell.userNameConstraint.constant = 170.0f;
        }else{
            cell.userNameConstraint.constant = sizeUserName.width;
        }
    }else{
        if ((sizeUserName.width + sizePosition.width) <= 170.0f) {
            cell.userNameConstraint.constant = sizeUserName.width;
            cell.posiTionConstraint.constant = sizePosition.width;
        }else{
            
            if (sizeUserName.width >110.0f) {
                cell.userNameConstraint.constant = 110.0f;
            }else{
                cell.userNameConstraint.constant = sizeUserName.width;
            }
            if (sizePosition.width > 60.0f) {
                cell.posiTionConstraint.constant = 60.0f;
            }else{
                cell.posiTionConstraint.constant = sizePosition.width;
            }
        }
    }
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PinLunCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
    
    
    UILabel *label = [[UILabel alloc] init];
    label.text = self.commentsList[indexPath.row][@"content"];
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:14];
    CGSize constranit = CGSizeMake(screenW-16, 2000.0f);
    CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constranit lineBreakMode:NSLineBreakByWordWrapping];
    self.tableView.height = self.tableView.contentSize.height;
    
    self.scrollView.contentSize = CGSizeMake(screenW, self.priceViewFir.height + self.tableView.height+20);
    
    return cell.frame.size.height + size.height-12;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


//展开收起事件
- (void)clickButtonAction:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    self.numHeight += 1;
    
    [self.tableView removeFromSuperview];
    
    if (self.numHeight%2==0) {
        
        self.priceViewFir.descriptionLabel.numberOfLines = 0;
        
    }else{
        self.priceViewFir.descriptionLabel.numberOfLines = 3;
        
    }
    
    
    
    [self setupPriceViewFir];
}







- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络请求


//获取更多评论
- (void)getMorePingLun
{

    
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    //page=页码&fundsId=资金id
    [muDicParameters setObject:_fundsId forKey:@"fundsId"];
    [muDicParameters setObject:[NSString stringWithFormat:@"%ld",self.page] forKey:@"page"];
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"manyComentFunds_app_funds.im"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        //NSLog(@"%@",dicInfo);

        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            NSArray *aryInff = [dicInfo objectForKey:@"data"][@"record"];
            
            for (int i = 0; i<aryInff.count; i++) {
                [self.commentsList addObject:aryInff[i]];
            }
            
            if (aryInff.count == 10) {
                self.scrollView.mj_footer.hidden = NO;
            }else {
                self.scrollView.mj_footer.hidden = YES;
            }

            
            [self.tableView reloadData];
            
        }else {

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];

        }
        
        [self.scrollView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.scrollView.mj_footer endRefreshing];
        [self showSingleIconBubble:error.localizedDescription];

    }];
}







#pragma mark - 下面控件的方法
//收藏
- (IBAction)CollectClick:(UIButton *)sender {
    
    
    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
        
        //NSLog(@"self.isFocus:%@",self.isFocus);
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        dic[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
        dic[@"token"] = [USER_DEFAULTS objectForKey:@"token"];
        dic[@"resId"] = self.fundsId;
        dic[@"resType"] = @(4);
        NSString *strURL = @"";
        if ([self.isFocus isEqualToString:@"否"]) {
            strURL = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"focusResources_app_action.im.lensum"];
            
        }else{
            strURL = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"focusResourcesCancel_app_action.im.lensum"];
        }
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:strURL parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            //NSLog(@"dicINFO:%@",dicInfo);
            if ([dicInfo[@"result"] integerValue] == 1) {
                if ([self.isFocus isEqualToString:@"否"]) {
                    [self.btnCollect setImage:[UIImage imageNamed:@"评论点赞图标"] forState:UIControlStateNormal];
                    
                    self.isFocus = @"是";
                }else{
                    [self.btnCollect setImage:[UIImage imageNamed:@"资讯-点赞"] forState:UIControlStateNormal];
                    
                    self.isFocus =@"否";
                }

            }
            if ([dicInfo[@"result"] integerValue] == 2) {
                if ([self.isFocus isEqualToString:@"否"] ) {
                    self.isFocus =@"否";
                }else{
                    self.isFocus = @"是";
                }

            }

            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self showSingleIconBubble:@"网络连接错误"];

        }];
        
        
        
    }else{
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
    

    
    
}

//评论
- (IBAction)commentClick:(UIButton *)sender {
//    self.page = 1;
//    PinLunVC * pVC = [[PinLunVC alloc]init];
//    
//    pVC.resId = self.dicData[@"fundsId"];
//    pVC.str = @"commentFunds_app_action.im.lensum";
//    [self.navigationController pushViewController:pVC animated:YES];
    WriteComment *writeView = [[WriteComment alloc] init];
    [writeView setFrame:CGRectMake(0, self.view.frame.size.height - 48, screenW, 48)];
    writeView.resId = self.dicData[@"fundsId"];
    writeView.urlStr = @"commentFunds_app_action.im.lensum";
    [self.view addSubview:writeView];
    
}
//分享
- (IBAction)shareClick:(UIButton *)sender {
    
    [ShareMsg shareMsgBOOLType:YES titleStr:nil contentStr:nil urlStr:nil imageAry:nil];
}
#pragma mark - 平台引荐
- (IBAction)platformClick:(UIButton *)sender {

    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
        self.recommendview.modalPresentationStyle=UIModalPresentationOverCurrentContext;
        [self presentViewController:self.recommendview animated:YES completion:nil];
        
    }else{
        [self showErrorWithTitle:@"请先登录!" autoCloseTime:2];
    }
    
    
}
//换算金额
-(NSString *)comperNumber:(NSString *)number
{
    CGFloat num1 = [number floatValue];
    NSString *strNum = @"";
    
    if (num1 >= 100000000) {
        
        strNum = [NSString stringWithFormat:@"%.2f亿元",num1/100000000];
    }else if (num1<100000000 && num1>=10000){
        
        strNum = [NSString stringWithFormat:@"%.2f万元",num1/10000];
    }else{
        
        strNum = [NSString stringWithFormat:@"%.2f元",num1];
    }
    return strNum;
}
@end
